const mongoose = require('mongoose')
const { Category } = require('../../schema')

mongoose.connect('mongodb://127.0.0.1:27017/sportswear').then()
const categoryCollection = mongoose.model('category', Category)

function insertCategory (category) {
    return new Promise((resolve, reject) => {
        categoryCollection.find({}).then(res => {
            if (res.length) {
                if (res[0].categoryList.includes(category)) {
                    reject('已经存在这个分类')
                    return
                }
                categoryCollection.updateOne({ name: 'sport' }, {
                    $push: {
                        categoryList: category
                    }
                }, {
                    multi: true
                }).then(res => {
                    resolve('分类:' + category + '添加成功!')
                })
            } else {
                const record = new categoryCollection({ name: 'sport', categoryList: [category] })
                record.save().then(res => {
                    resolve('分类:' + category + '添加成功!')
                })
            }
        })
    })
}

function readCategoryList () {
    return new Promise((resolve, reject) => {
        categoryCollection.findOne({}).then(res => {
            if (res) {
                resolve(res.categoryList)
            } else {
                resolve([])
            }
        }).catch(err => {
            reject(err)
        })
    })
}

function modifyCategoryList (category, newval) {
    return new Promise(resolve => {
        categoryCollection.updateOne({
            categoryList: category
        }, {
            $set: {
                'categoryList.$': newval
            }
        }).then(res => {
            if (res.modifiedCount) {
                resolve('修改分类成功')
            } else {
                resolve('没有找到分类')
            }
        })
    })
}

function removeCategoryList (category) {
    return new Promise((resolve, reject) => {
        categoryCollection.findOne({ categoryList: category }).then(res => {
            if (res) {
                categoryCollection.updateOne({ name: 'sport' }, {
                    $pull: {
                        categoryList: category
                    }
                }).then(() => {
                    resolve('移除' + category + '分类成功')
                }, () => {
                    reject('移除' + category + '分类失败')
                })
            } else {
                reject(category + '分类不存在')
            }
        })
    })
}

module.exports = {
    insertCategory,
    readCategoryList,
    modifyCategoryList,
    removeCategoryList
}
